package com.lkr.webapp.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用工具类
 *
 * @author lkr
 * @date 2019-02-01, Fri
 */
public class CommonUtil {

    private static final String CHAR_1 = "&";
    private static final String CHAR_2 = "=";

    /**
     * 获取url中的参数键值对，多个value对应一个key只取第一个值
     *
     * @param url foo
     * @return map模型
     */
    public static Map<String, String> getQueryParams(String url) {
        Map<String, String> params = new HashMap<>(16);
        try {
            String[] urlParts = url.split("\\?");
            if (urlParts.length > 1) {
                String query = urlParts[1];
                //"?hello=1&id=2"
                for (String param : query.split(CHAR_1)) {
                    String[] pair = param.split(CHAR_2);
                    String key = URLDecoder.decode(pair[0], "UTF-8");
                    String value = "";
                    if (pair.length > 1) {
                        value = URLDecoder.decode(pair[1], "UTF-8");
                    }
                    params.put(key, value);
                }
            }
        } catch (UnsupportedEncodingException ignored) {
        }
        return params;
    }


    /**
     * 获取url中某个value
     *
     * @param url foo
     * @param key key
     * @return value
     */
    public static String getValueByKeyInUrl(String url, String key) {
        return getQueryParams(url).get(key);
    }
}
